package model

import (
	"ginTea/utils/errmsg"
	"time"

	"github.com/jinzhu/gorm"
)

type Address struct {
	ID         uint      `gorm:"primary_key" json:"id"`
	CreatedAt  time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt  time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	UserId     int       `gorm:"column:user_id" json:"user_id"`
	Name       string    `gorm:"column:name" json:"name"`
	Tel        string    `gorm:"column:tel" json:"tel"`
	ReceiveAdd string    `gorm:"column:receive_add" json:"receive_add"`
}

// 新增地址
func CreateAddress(data *Address) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 删除地址
func DeleteAddress(id int) int {
	var data Address
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err = db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR
}

// 获取地址列表
func GetAddressList(user_id int) ([]Address, int) {
	var data []Address
	var total int
	err = db.Find(&data).Where("id=?", user_id).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return data, total
}

// 编辑收货地址
func UpdateAddress(data *Address) int {
	var user Address
	var maps = make(map[string]interface{})
	maps["name"] = data.Name
	maps["tel"] = data.Tel
	maps["receive_add"] = data.ReceiveAdd
	err = db.Model(&user).Where("id=? AND user_id != ?", data.UserId, data.ID).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
